<template v-if="bye">
  <div style="padding: 14px 14px 0">
    <a-row justify="space-between" align="middle">
      <a-col>
        <RouteTitle />
      </a-col>
    </a-row>
    <a-table :dataSource="dataSource" :columns="columns" :pagination="pagination" @change="handleTableChange"
      :loading="loading" style="margin-top: 10px" :scroll="{ x: 1500 }"
      :row-selection="activeKey == 0 ? { selectedRowKeys: selectedRowKeys, onChange: onSelectChange } : null"
      :rowKey="activeKey == 0 ? (record) => record.id : null">
      <template #title>
        <div style="display: flex;justify-content: space-between;align-items: center;">
          <a-tabs v-model:activeKey="activeKey">
            <a-tab-pane v-for="item in tabsList" :key="item.key" :tab="item.title" />
          </a-tabs>
          <a-button size="small" type="primary" @click="onBatchCancel" v-if="activeKey == 0"
            :disabled="!selectedRowKeys.length">批量取消</a-button>
        </div>
      </template>
      <template #bodyCell="{ column, record }">
        <!-- 发布平台 -->
        <template v-if="column.key == 'film_release'">
          <a-space>
            <a-image :preview="false" :width="30" :height="30" :src="platformList?.find(
              (it) => it?.key === record?.film_release?.platform
            )?.image
              " />
            <span>{{
              platformList?.find(
                (it) => it?.key === record?.film_release?.platform
              )?.value
            }}</span>

          </a-space>
          <a-divider style="height: 1px;" dashed />
          <span style="font-size:12px;;line-height:12px;color:#999">创建时间：{{ record?.created_at }}</span>
          <div style="font-size:12px;;line-height:12px;color:#999;margin-top: 3px;">发布方式：{{
            record?.film_release?.release_type == 2 ? '定时发布' : '立即发布' }}</div>
          <a-divider style="height: 1px;" dashed />
          <a-space style="font-size:12px;;line-height:12px;color:#999">
            <span>使用账号：{{ record?.platform_account?.nickname }} <a-image :preview="false" :width="25" :height="25"
                :style="{ borderRadius: '15px', alignItems: 'center', justifyContent: 'center', display: 'unset' }"
                :src="record?.platform_account?.avatar" /></span>
          </a-space>

        </template>
        <!-- 成片 -->
        <template v-if="column.key == 'multimedia'">
          <div class="image_con" v-if="record?.multimedia?.material_url" @click="handlePlay(record?.multimedia || {})">
            <video :src="record?.multimedia?.material_url" v-if="!record.thumb_url"></video>
            <img :src="record.thumb_url" alt="" v-if="record.thumb_url" />
            <div class="operate_con">
              <cu-icon type="icon-24gl-playCircle" style="font-size: 36px; color: #fff" />
            </div>
            <div class="bottom_con">
              <span>视频</span>
              <cu-icon type="icon-changjing" style="font-size: 14px; color: #fff; margin-left: 3px" />
            </div>
          </div>
          <div v-else>-</div>
        </template>
        <!-- 发布状态 -->
        <template v-if="column.key == 'release_status'">
          <div class="release_status_box">
            <a-tag color="blue" v-if="record.release_status == 0">{{
              record?.release_status_text
            }}</a-tag>
            <a-tag color="processing" v-if="record.release_status == 1">{{
              record?.release_status_text
            }}</a-tag>
            <a-tag color="success" v-if="record.release_status == 2">{{
              record?.release_status_text
            }}</a-tag>

            <template v-if="record.release_status == 3">
              <a-tag style="margin-bottom: 10px" color="error">{{ record?.release_status_text }}
              </a-tag>
              <span style="color: #5a5a5a; font-size: 13px">失败原因:{{ record?.api_failed }}</span>
            </template>

            <a-tag color="default" v-if="record.release_status == 4">{{
              record?.release_status_text
            }}</a-tag>
            <a-tag color="default" v-if="record.release_status == 5">{{
              record?.release_status_text
            }}</a-tag>
          </div>


        </template>
        <!-- 取消任务 -->
        <template v-if="column.key == 'cancel_task'">
          <a-popconfirm title="确定取消该发布任务吗?" ok-text="确定" cancel-text="取消" @confirm="cancelTask(record)"
            @cancel="cancel">
            <a-button size="small">取消任务</a-button>
          </a-popconfirm>

        </template>
        <!-- 发布状态 -->
        <template v-if="column.key == 'play_count'">
          {{ record?.release_status_text == '发布成功' ? record?.play_count : '--' }}
        </template>
        <template v-if="column.key == 'comment_count'">
          {{ record?.release_status_text == '发布成功' ? record?.comment_count : '--' }}
        </template>
        <!-- 允许他人保存视频 -->
        <template v-if="column.key == 'download_text'">
          <div>
            {{ record.download_text || "--" }}
          </div>
        </template>
        <!-- 设置谁可以看 -->
        <template v-if="column.key == 'visibility_type_text'">
          <div>
            {{ record.visibility_type_text || "--" }}
          </div>
        </template>
        <!-- 发布时间 -->
        <template v-if="column.key == 'release_time'">
          <div>
            {{ record.release_time || "--" }}
          </div>
        </template>
        <!-- 操作 -->
        <template v-if="column.key == 'actions'">
          <a-popover v-model:visible="record.actionModalVisible" trigger="click">
            <template #content>
              <div class="action_content">
                <a-form :model="actionForm" ref="actionFormRef" :rules="actionFormRules" layout="inline">
                  <a-form-item name="release_type">
                    <a-radio-group v-model:value="actionForm.release_type">
                      <a-radio :value="1">立即发布</a-radio>
                      <a-radio :value="2">
                        定时发布
                      </a-radio>
                    </a-radio-group>
                  </a-form-item>
                  <a-form-item v-if="actionForm.release_type == 2" name="release_time">
                    <a-time-range-picker v-model="actionForm.release_time" format="HH:mm"/>
                  </a-form-item>
                </a-form>
                <div style="display: flex;justify-content: center;">
                  <a-button @click="record.actionModalVisible = false" size="small" type="primary">关闭</a-button>
                </div>
              </div>

            </template>
            <a-button type="primary" size="small" @click="record.actionModalVisible = true">操作</a-button>
          </a-popover>

        </template>
      </template>
    </a-table>
    <!-- </template> -->

    <template v-if="activeKeyParent === 'pic'">
      <image-text-record />
    </template>
  </div>

  <PreviewModal :visible="previewVisible" :title="previewParams.title" :url="previewParams.url"
    :type="previewParams.type" @onCancel="previewVisible = false" />
</template>

<script>
import { defineComponent, reactive, toRefs, computed, watch } from "vue";
import { Form } from "ant-design-vue";
import request from "@/common/utils/request";
import PreviewModal from "@/components/PreviewModal/index.vue";
import { getPlatformList } from "./service/accountManageApi";
import ImageTextRecord from "./modules/ImageTextRecord.vue";
import { onBeforeRouteLeave } from "vue-router";

export default defineComponent({
  name: "ReleaseRecord",
  components: {
    PreviewModal,
    ImageTextRecord,
  },
  setup(props, { emit }) {
    const state = reactive({
      bye: true,

      previewVisible: false,
      previewParams: {
        title: "",
        url: "",
        type: "video",
      },
      count: 0,
      dataSource: [],
      platform: undefined,
      columns: [
        {
          title: "发布平台",
          dataIndex: "film_release",
          key: "film_release",
          width: 180,
        },
        {
          title: "成片",
          dataIndex: "multimedia",
          key: "multimedia",
          width: 160,
        },
        {
          title: "标题",
          dataIndex: "title",
          key: "title",
        },
        {
          title: "发布状态",
          dataIndex: "release_status",
          key: "release_status",
          width: 260,
        },
        {
          title: "播放量",
          dataIndex: "play_count",
          key: "play_count",
        },
        {
          title: "评论数",
          dataIndex: "comment_count",
          key: "comment_count",
        },
        {
          title: "允许他人保存视频",
          dataIndex: "download_text",
          key: "download_text",
        },
        {
          title: "设置谁可以看",
          dataIndex: "visibility_type_text",
          key: "visibility_type_text",
        },
        {
          title: "发布时间",
          dataIndex: "release_time",
          key: "release_time",
          sort: true,
        },
      ],

      loading: false,
      page: 1,
      pageSize: 10,
      total: 0,
      activeKeyParent: "video",
      platformList: [],
      tabsParent: [
        {
          title: "视频发布记录",
          icon: "icon-changjing",
          key: "video",
        },
        // {
        //   title: "图文发布记录",
        //   icon: "icon-tupian2",
        //   key: "pic",
        // },
      ],
      activeKey: -1,
      tabsList: [
        {
          title: "全部",
          key: -1,
        },
        {
          title: "待发布",
          key: 0,
        },
        {
          title: "发布中",
          key: 1,
        },
        {
          title: "发布成功",
          key: 2,
        },
        {
          title: "发布失败",
          key: 3,
        },
        {
          title: "已删除",
          key: 4,
        },
      ],
      selectedRowKeys: [],//取消发布列表
      // 操作表单
      actionForm: {
        release_type: '',
        release_time: []
      },
      // 操作表单校验
      actionFormRules: [
      ]
    });

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
      showQuickJumper: true,
    }));

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getDataList();
    };

    const handlePlay = (record) => {
      state.previewParams = {
        title: record?.material_name,
        url: record?.material_url,
        type: "video",
      };
      state.previewVisible = true;
    };

    const onClose = () => {
      emit("onCancel");
    };

    const onConfirm = () => {
      emit("onConfirm");
    };

    const getDataList = () => {
      state.loading = true;
      if (state.activeKeyParent === "pic") {
        state.dataSource = [];
        state.page = 1;
        state.total = 0;
        return;
      }
      const params = {
        account_id: props.data?.id,
        status: state.activeKey,
        page: state.page,
        pageSize: state.pageSize,
        platform: state.platform,
      };

      request
        .get(
          "work_ai",
          state.activeKey != 4
            ? "/user/filmrelease/push/list"
            : "/user/filmrelease/push/list/delete",
          params
        )
        .then((res) => {
          state.dataSource = res.list.data;
          state.dataSource.forEach(item => {
            item.actionModalVisible = false // 操作的弹窗
          })
          state.total = res.list.total;
          state.loading = false;
          state.selectedRowKeys = []
        })
        .catch(() => {
          state.loading = false;
        });
    };

    const getPFList = () => {
      getPlatformList().then((res) => {
        state.platformList = res.result;
      });
    };

    const init = () => {
      getPFList();
      getDataList();
    };

    watch(
      () => state.platform,
      () => {
        state.page = 1;
        getDataList();
      }
    );

    watch(
      () => state.activeKey,
      () => {
        state.page = 1;
        if (state.activeKey === -1 || state.activeKey === 2) {
          if (!state.columns.some(column => column.key === "play_count")) {
            state.columns.splice(4, 0, { key: "play_count", title: "播放量", dataIndex: "play_count" });
          }
          if (!state.columns.some(column => column.key === "comment_count")) {
            state.columns.splice(5, 0, { key: "comment_count", title: "评论数", dataIndex: "comment_count" });
          }
        } else {
          // 移除 play_count 列
          state.columns = state.columns.filter(column => column.key !== "play_count");
          state.columns = state.columns.filter(column => column.key !== "comment_count");
        }
        // 待发布有取消任务操作
        if (state.activeKey == 0) {
          state.columns.splice(4, 0, {
            title: '取消任务',
            dataIndex: "cancel_task",
            key: "cancel_task",
            width: 260,
            align: 'center'
          });
        }
        else {
          let findIndex = state.columns.findIndex(column => column.key === "cancel_task");
          if (findIndex !== -1) {
            state.columns.splice(findIndex, 1);
          }
        }
        // 发布失败有操作按钮
        if (state.activeKey == 3) {
          state.columns.push({
            title: '操作',
            dataIndex: "actions",
            key: "actions",
            width: 100,
            fixed: 'right',
            align: 'center'
          });
        } else {
          let findIndex = state.columns.findIndex(column => column.key === "actions");
          if (findIndex !== -1) {
            state.columns.splice(findIndex, 1);
          }
        }
        getDataList();
      }
    );

    watch(
      () => state.activeKeyParent,
      () => {
        state.platform = undefined;
        state.activeKey = -1;
        state.page = 1;
        getDataList();
      }
    );

    init();
    onBeforeRouteLeave((to, from, next) => {
      state.bye = false
      next(true)
    });
    // 列表选中事件
    const onSelectChange = selectedRowKeys => {
      state.selectedRowKeys = selectedRowKeys;
    };
    // 批量取消
    const onBatchCancel = () => {

    }
    // 单个取消
    const cancelTask = (record) => {
      request.get('/user/task/cancel', { params: { id: record.id } })
        .then(() => {
          message.success('任务取消成功');
          // resolve(true);
        })
        .catch((error) => {
          message.error('任务取消失败');
          // reject(error);
        });
    }
    return {
      ...toRefs(state),
      onConfirm,
      onClose,
      handlePlay,
      pagination,
      handleTableChange,
      onSelectChange,
      onBatchCancel,
      cancelTask
    };
  },
});
</script>

<style lang="less" scoped>
.image_con {
  cursor: pointer;
  width: 140px;
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #000;
  position: relative;

  video {
    max-width: 100%;
    max-height: 100%;
  }

  img {
    max-width: 100%;
    max-height: 100%;
    object-fit: cover;
  }

  .operate_con {
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    position: absolute;
    display: none;
    background-color: rgba(0, 0, 0, 0.5);
  }

  &:hover {
    .operate_con {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .bottom_con {
    width: 100%;
    height: 30px;
    left: 0;
    bottom: 0;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    color: #fff;
    font-size: 12px;
    padding-left: 5px;
  }
}

.card {
  width: 100%;
  padding: 20px 24px;
  background: #fff;
  margin-bottom: 20px;

  .text-bold {
    font-weight: 700;
  }
}

:deep(.ss-tabs-top > .ss-tabs-nav) {
  margin: 0;
}

:deep(.ss-table-title) {
  padding-bottom: 0;
}

.release_status_box {
  // max-width: 260px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 11;
  overflow: hidden;
}
</style>
